<?php

namespace App\Jobs;

use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Chanjet\LogFormatRecord;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class Inventory implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $data;
    public $tries = 3;      // Laravel 自动重试次数（包括首次执行）
    public $timeout = 60;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        $data = $this->data;
        try {
            // 参数校验
            if (!isset($data["mangerinfo"], $data["api"], $data["param"])) {
                throw new \InvalidArgumentException("缺少必要参数: mangerinfo/api/param");
            }

            // 检查是否允许请求
            if (!TplusCommonController::isAllowRequestTplus($data["mangerinfo"])) {
                throw new \InvalidArgumentException("Chanjet API 请求被禁止");
            }

            //请求存货前，查看是否已创建计量单位,接口调不通 反馈给程阳，需要华坤手动新增 计量单位组
            //$this->checkUnitName($data);

            // 执行 API 请求
            $api = $data["api"];
            $param = $data["param"];
            $res = ChanjetRequest::getInstance()->$api($param, $data["mangerinfo"]['org_id']);

            // 处理不同 API 的响应
            $this->validateApiResponse($api, $res);

            Log::info("Chanjet 存货/存货分类,同步成功", ['data' => $data]);
        } catch (\Throwable $e) {
            $this->handleFailure($e);
        }
    }

    protected function validateApiResponse(string $api, $response)
    {
        switch ($api) {
            case "inventoryClassCreate":
            case "inventoryCreate":
                if (!is_null($response)) {
                    throw new \RuntimeException("Chanjet {$api} 请求失败");
                }
                break;
            case "inventoryCreateBatch":
                if (!isset($response["Success"]) || $response["Success"] !== true) {
                    throw new \RuntimeException("Chanjet {$api} 批量请求失败");
                }
                foreach ($response["Data"] ?? [] as $item) {
                    if ($item["Success"] !== true) {
                        throw new \RuntimeException("Chanjet {$api} 存在失败子项");
                    }
                }
                break;
            case "inventoryUpdate":
                if (!is_null($response)) {
                    throw new \RuntimeException("Chanjet {$api} 请求失败");
                }
                break;
        }
    }
    public function checkUnitName($data = []){
        if(in_array($data["api"],["inventoryCreate","inventoryCreateBatch"])){
            $res = ChanjetRequest::getInstance()->UnitGroupQuery(["param"=>[""=>""]], $data["mangerinfo"]['org_id']);
            $is_exist_unitname = false;
            if(isset($res['Data'])){
                foreach ($res["Data"] ?? [] as $item) {
                    if($item['Name'] == "吨/件"){
                        $is_exist_unitname = true;
                        break;
                    }
                }
            }
            //不存在计量单位组，新增
            if(!$is_exist_unitname) {
                ChanjetRequest::getInstance()->UnitGroupCreate(
                    [
                        "dto"=>[
                            "Name"=>"吨/件",
                            "UnitDTOs"=>[
                                [
                                    "Name" => "吨",
                                    "ChangeRate" => "1",
                                    "IsMainUnit" => true,
                                ],
                                [
                                    "Name" => "件",
                                    "ChangeRate" => "1",
                                    "IsMainUnit" => false,
                                    "ChangeType" =>["id" => "24"],//换算类型枚举id  152浮动 24 固定
                                ],
                            ]
                        ]
                    ],
                    $data["mangerinfo"]['org_id']
                );
            }
        }
        return true;
    }

    protected function handleFailure(\Throwable $e)
    {
        // 参数错误立即失败，不重试
        if ($e instanceof \InvalidArgumentException) {
            $this->failed($e);
            return;
        }

        // 可重试错误：达到最大尝试次数后标记失败
        if ($e instanceof \RuntimeException) {
            if ($this->attempts() >= $this->tries) {
                $this->failed($e);
            }else{
                throw $e;
            }
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info($exception->getMessage().'failed方法');
        $this->data["error"] = $exception->getMessage();
        $this->data["res"] = "Chanjet 存货/存货分类,同步失败";
        LogFormatRecord::error($this->data);
        return;
    }
}
